package com.itsu.manage.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.itsu.commons.annotations.NoInterceptor;
import com.itsu.manage.interceptor.UserThreadLocal;
import com.itsu.manage.service.AppManageUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("system")
public class SystemController {

    private LineCaptcha lineCaptcha;

    private Logger logger = LoggerFactory.getLogger(SystemController.class);

    @Autowired
    AppManageUserService appManageUserService;


    @Autowired
    RedisTemplate<String, String> redisTemplate;

    //登录
    @NoInterceptor
    @PostMapping("users/login")
    public ResponseEntity login(@RequestBody Map<String, String> map) {
        Map<String, Object> data = appManageUserService.login(map);
        return ResponseEntity.ok(data);
    }

    //登录校验
    @NoInterceptor
    @GetMapping("users/verification")
    public ResponseEntity verification(HttpServletResponse response,@RequestParam("uuid") String uuid) {
        System.out.println(uuid);
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        // 定义图片的显示大小
        lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 打印日志
            logger.info("生成的验证码:{}", lineCaptcha.getCode());
            //
            redisTemplate.opsForValue().set("IMAGE_CODE" + uuid, lineCaptcha.getCode(), 5, TimeUnit.MINUTES);
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(null);
    }

    //登录人详情
    @PostMapping("users/profile")
    public ResponseEntity profile() {
        Map<String, String> map = appManageUserService.loginProfile();
        return ResponseEntity.ok(map);
    }

    //登出
    @PostMapping("users/logout")
    public ResponseEntity logout(HttpServletResponse response) {
        UserThreadLocal.remove();
        return ResponseEntity.ok(null);
    }


}
